"use strict";
$(document).ready(function() {

  var $table = $('#stocks').DataTable({
    bProcessing : true,
    bServerSide : true,
    sPaginationType : 'full_numbers',
    scrollX: true,
    oLanguage : {
      sLengthMenu : '每页显示 _MENU_ 条',
      sInfo : '第 _START_ -  _END_ 条，共 _TOTAL_ 条',
      sInfoFiltered : '',
      sInfoEmpty : '没有数据',
      sZeroRecords : '没有数据',
      sProcessing : '正在加载数据...',
      oPaginate : {
        sFirst : '首页',
        sPrevious : '前一页',
        sNext : '后一页',
        sLast : '末页'
      },
      sSearch : '检索',
      sSearchPlaceholder : '输入产品、货架的编号或名称'
    },
    columns : [ {
      data : 'id'
    }, {
      data : 'productId'
    }, {
      data : 'productName'
    }, {
      data : 'quantity'
    }, {
      data : 'rackId'
    }, {
      data : 'layer',
      render : function(data, type, row, meta) {
        return data + '层' + row.col + '号';
      }
    }, {
      data : 'vendor'
    }, {
      data : 'phone'
    }, {
      data : 'receiveTime',
      className : 'text-center',
      render : function(data, type, row, meta) {
        return $.format.date(data, 'yyyy-M-d H:mm')
      }
    } ],
    order: [ [4, 'asc'] ],
    ajax : function(data, callback, settings) {
      var d = $.customParam(data);
      $.ajax({
        dataType : 'json',
        method : 'POST',
        url : 'stocks_processing.json',
        data : d,
        success : function(json) {
          var error = json.error || json.sError;
          if (error) {
            alert(error);
            return;
            // _fnLog( oSettings, 0, error );
          }
          settings.json = json;
          callback(json);
        }
      });
    }
  });
  $('#stocks tbody').on('click', 'tr', function() {
    if ($(this).hasClass('selected')) {
      $(this).removeClass('selected');
    } else {
      $table.$('tr.selected').removeClass('selected');
      $(this).addClass('selected');
    }
  });

  var refreshImages = function(productId, currentName, imageDiv, listDiv) {
    var name = currentName;
    $.ajax({
      url : 'product/' + productId + '/images.json',
      method : 'GET',
      success : function(ret) {
        var html = '';
        for (var i = 0; i < ret.length; i++) {
          var file = ret[i];
          if (!name) {
            name = file.name;
          }
          if (i > 0) {
            html += '&nbsp;';
          }
          html += '<a href="javascript:void(0);"';
          if (name == file.name) {
            html += ' class="selected"';
          }
          html += '>' + file.name + '</a>';
        }
        $(listDiv).html(html);
        if (name && name.length > 0) {
          $(imageDiv).html('<img src="product/' + productId + '/' + name + '" />');
        } else {
          $(imageDiv).html('');
        }
      }
    });
  };
  
  // 新增处理
  $('#creatediv form').validate({
    rules : {
      productid : {
        required : true
      },
      rackid : {
        required : true
      },
      layer: {
        required : true,
        digits: true,
        min: 1
      },
      col: {
        required : true,
        digits: true,
        min: 1
      },
      quantity: {
        required : true,
        digits: true,
        min: 1
      }
    },
    messages : {
      productid : {
        required : '产品编号不能为空'
      },
      rackid : {
        required : '货架编号不能为空'
      },
      layer: {
        required : '所在层必须填写',
        digits: '所在层必须是整数',
        min: '所在层必须大于0'
      },
      col: {
        required : '所在号必须填写',
        digits: '所在号必须是整数',
        min: '所在号必须大于0'
      },
      quantity: {
        required : '产品数量必须填写',
        digits: '产品数量必须是整数',
        min: '产品数量必须大于0'
      }
    },
    errorClass : 'has-error',
    validClass : 'has-success',
    highlight : function(element, errorClass, validClass) {
      var $c = $(element).closest('div.form-group');
      $c.addClass(errorClass).removeClass(validClass);
    },
    unhighlight : function(element, errorClass, validClass) {
      var $c = $(element).closest('div.form-group');
      $c.removeClass(errorClass).addClass(validClass);
    }
  });
  var addDlg;
  $('#btnAdd').click(function() {
    addDlg = layer.open({
      type : 1,
      title : false,
      area : '800px',
      closeBtn : true,
      shadeClose : false,
      content : $('#creatediv')
    });
    $('#creatediv form').get(0).reset();
    $('#add_productname').text('');
    $('#add_vendor').text('');
    $('#add_images').html('');
    $('#creatediv .images').html('');
    $('#creatediv form').validate().resetForm();
    $('#add_productid')[0].focus();
  });
  $('#add_productid').blur(function(){
    $('#add_productname').text('');
    $('#add_vendor').text('');
    var productId = $(this).val();
    if(productId == '') {
      return;
    }
    $.ajax({
      url : 'product/' + productId,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        $('#add_productname').text(ret.name);
        $('#add_vendor').text(ret.vendor);
      }
    });
    refreshImages(productId, null, $('#creatediv .images'), $('#add_images'));
  });
  $('#add_images').on('click', 'a', function() {
    var $this = $(this);
    var productId = $('#add_productid').val();
    $('#add_images a').removeClass('selected');
    $this.addClass('selected');
    $('#creatediv .images').html('<img src="product/' + productId + '/' + $this.text() + '" />');
  });  
  $('#add_rackid').blur(function(){
    var rackId = $(this).val();
    $.ajax({
      url : 'rack/' + rackId,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        if(!ret) {
          alert('货架编号不存在！');
        }
      }
    });
  });
  $('#add_productid').keydown(function(e) {
    if (e.keyCode == 13) {
      $('#add_rackid').focus();
    }
  });
  $('#add_rackid').keydown(function(e) {
    if (e.keyCode == 13) {
      $('#add_quantity').focus();
    }
  });
  
  $('#creatediv .btn-default').click(function() {
    layer.close(addDlg);
  });
  $('#creatediv .btn-primary').click(function() {
    if (!$('#creatediv form').valid()) {
      layer.alert('请修正输入错误！');
    } else {
      var data = {
          id: 0,
          productId: $('#add_productid').val(),
          productName: $('#add_productname').text(),
          vendor: $('#add_vendor').text(),
          rackId: $('#add_rackid').val(),
          layer: $('#add_layer').val(),
          col: $('#add_col').val(),
          quantity: $('#add_quantity').val()
      };
      data['_method'] =  'POST';
      $.ajax({
        url : 'stock',
        method : 'POST',
        data : data,
        success : function(ret) {
          layer.close(addDlg);
          $table.ajax.reload();
        }
      });
    }
  });

  // 编辑处理
  $('#editdiv form').validate({
    rules : {
      layer: {
        required : true,
        digits: true,
        min: 1
      },
      col: {
        required : true,
        digits: true,
        min: 1
      },
      quantity : {
        required : true,
        digits: true,
        min: 1
      }
    },
    messages : {
      layer: {
        required : '所在层必须填写',
        digits: '所在层必须是整数',
        min: '所在层必须大于0'
      },
      col: {
        required : '所在号必须填写',
        digits: '所在号必须是整数',
        min: '所在号必须大于0'
      },
      quantity : {
        required : '产品数量必须填写',
        digits: '产品数量必须是整数',
        min: '产品数量必须大于0'
      }
    },
    errorClass : 'has-error',
    validClass : 'has-success',
    highlight : function(element, errorClass, validClass) {
      var $c = $(element).closest('div.form-group');
      $c.addClass(errorClass).removeClass(validClass);
    },
    unhighlight : function(element, errorClass, validClass) {
      var $c = $(element).closest('div.form-group');
      $c.removeClass(errorClass).addClass(validClass);
    }
  });
  var editDlg;
  var editStock;
  $('#btnEdit').click(function() {
    var data = $table.row('.selected').data();
    if (!data) {
      layer.alert('请选中待更改的库存记录！');
      return;
    }
    var loadIndex = layer.load();
    $.ajax({
      url : 'stock/' + data.id,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        layer.close(loadIndex);
        editDlg = layer.open({
          type : 1,
          title : false,
          area : '800px',
          closeBtn : true,
          shadeClose : false,
          content : $('#editdiv')
        });
        $('#editdiv form').get(0).reset();
        $('#editdiv form').validate().resetForm();
        editStock = ret;
        $('#edit_id').text(editStock.id);
        $('#edit_productid').val(editStock.productId);
        $('#edit_productname').text(editStock.productName);
        $('#edit_vendor').text(editStock.vendor);
        $('#edit_rackid').val(editStock.rackId);
        $('#edit_layer').val(editStock.layer);
        $('#edit_col').val(editStock.col);
        $('#edit_quantity').val(editStock.quantity);
        refreshImages(editStock.productId, null, $('#editdiv .images'), $('#edit_images'));
      }
    });
  });  
  $('#edit_productid').blur(function(){
    $('#edit_productname').text('');
    $('#edit_vendor').text('');
    var productId = $(this).val();
    if(productId == '') {
      return;
    }
    $.ajax({
      url : 'product/' + productId,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        $('#edit_productname').text(ret.name);
        $('#edit_vendor').text(ret.vendor);
      }
    });
    refreshImages(productId, null, $('#editdiv .images'), $('#edit_images'));
  });
  $('#edit_rackid').blur(function(){
    var rackId = $(this).val();
    $.ajax({
      url : 'rack/' + rackId,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        if(!ret) {
          alert('货架编号不存在！');
        }
      }
    });
  });
  $('#edit_images').on('click', 'a', function() {
    var $this = $(this);
    var productId = editStock.productId;
    $('#edit_images a').removeClass('selected');
    $this.addClass('selected');
    $('#editdiv .images').html('<img src="product/' + productId + '/' + $this.text() + '" />');
  });  
  $('#editdiv .btn-default').click(function() {
    layer.close(editDlg);
  });
  $('#editdiv .btn-primary').click(function() {
    if (!$('#editdiv form').valid()) {
      layer.alert('请修正输入错误！');
    } else {
      editStock.productId = $('#edit_productid').val();
      editStock.productName = $('#edit_productname').text();
      editStock.vendor = $('#edit_vendor').text();
      editStock.rackId = $('#edit_rackid').val();
      editStock.layer = $('#edit_layer').val();
      editStock.col = $('#edit_col').val();
      editStock.quantity = $('#edit_quantity').val();
      editStock['_method'] = 'PUT';
      $.ajax({
        url : 'stock/' + editStock.id,
        method : 'POST',
        data : editStock,
        success : function(ret) {
          layer.close(editDlg);
          $table.ajax.reload();
        }
      });
    }
  });
  

  // 删除处理
  $('#btnDel').click(function() {
    var data = $table.row('.selected').data();
    if (!data) {
      layer.alert('请选中待删除的库存记录！');
      return;
    }
    layer.confirm('确认要删除库存记录\"' + data.productName + ': ' + data.rackId + '\"？', function(index) {
      $.ajax({
        url : 'stock/' + data.id,
        method : 'POST',
        data : {
          _method : 'DELETE'
        },
        success : function(ret) {
          layer.close(index);
          $table.ajax.reload();
        }
      });
    });
  });

});